import torch
import torch.nn as nn
import random
import math
import copy
import torch.nn.functional as F

# tokenizer = RobertaTokenizer.from_pretrained("chinese_roberta_wwm_ext_pytorch")
# g_vocab_size = g_tokenizer.vocab_size
# g_bert = RobertaModel.from_pretrained('chinese_roberta_wwm_ext_pytorch')
class PositionalEncoding(nn.Module):

    def __init__(self, d_model, dropout=0.1, max_len=5000):
        super(PositionalEncoding, self).__init__()
        self.dropout = nn.Dropout(p=dropout)

        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)
        self.register_buffer('pe', pe)

    def forward(self, x):
        x = x + self.pe[:x.size(0), :]
        return self.dropout(x)

class Seq2SeqTransformer(nn.Module):
    def __init__(self, src_vocab_size, tgt_vocab_size, embed_size, ntoken, device, d_model=2048, nhead=6, nlayers=2, dropout=0.1, activation='gelu'):
        super(Seq2SeqTransformer,self).__init__()
        self.device = device
        self.embed_size = embed_size
        encoder_layers = nn.TransformerEncoderLayer(embed_size, nhead, d_model, dropout, activation)
        self.transformer_encoder = nn.TransformerEncoder(encoder_layers, nlayers)
        decoder_layers = nn.TransformerDecoderLayer(embed_size, nhead, d_model, dropout, activation)
        self.transformer_decoder = nn.TransformerDecoder(decoder_layers, nlayers)
        self.pos_encoder = PositionalEncoding(embed_size, dropout)
        self.src_embedder = nn.Embedding(src_vocab_size, embed_size)
        self.tgt_embedder = nn.Embedding(tgt_vocab_size, embed_size)
        self.fc_out = nn.Linear(embed_size, tgt_vocab_size)
        self.init_weights()

    def init_weights(self):
        initrange = 0.02
        nn.init.uniform_(self.src_embedder.weight, -initrange, initrange)
        nn.init.uniform_(self.tgt_embedder.weight, -initrange, initrange)
        nn.init.zeros_(self.fc_out.weight)
        nn.init.uniform_(self.fc_out.weight, -initrange, initrange)

    def _generate_square_subsequent_mask(self, sz):
        mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
        mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
        return mask

    def forward(self, input_variable, input_lengths=None, target_variable=None,
                teacher_forcing_ratio=0, parallel=True):
        output_len = 50
        if teacher_forcing_ratio != 0:
            output_len, batch_size = target_variable.size()
        else:
            batch_size = input_variable.size(1)
        embedded_input = self.src_embedder(input_variable) * math.sqrt(self.embed_size)
        embedded_input = self.pos_encoder(embedded_input)
        
        src_output = self.transformer_encoder(embedded_input)
        teacher_force = (random.random() < teacher_forcing_ratio)
        decoder_outputs = []
        # teacher_force = True
        if teacher_force:
            embedded_output = self.tgt_embedder(target_variable)
            embedded_output = self.pos_encoder(embedded_output)
            tgt_mask = self._generate_square_subsequent_mask(output_len).to(self.device)
            decoder_output = self.transformer_decoder(tgt=embedded_output,
                                                      memory=src_output,
                                                      tgt_mask=tgt_mask)
            predictions = self.fc_out(decoder_output)
            return F.log_softmax(predictions, dim=-1)
            # for di in range(predictions.size(0)):
            #     step_output = predictions[di, :, :]
            #     step_output = F.log_softmax(step_output, dim=-1)
            #     decoder_outputs.append(step_output)
        elif parallel:
            with torch.no_grad():
                embedded_output = self.tgt_embedder(target_variable)
                embedded_output = self.pos_encoder(embedded_output)
                tgt_mask = self._generate_square_subsequent_mask(output_len).to(self.device)
                decoder_output = self.transformer_decoder(tgt=embedded_output,
                                                        memory=src_output,
                                                        tgt_mask=tgt_mask)
                predictions = self.fc_out(decoder_output)
                predictions = F.log_softmax(predictions, dim=-1)

            embedded_output_2 = self.tgt_embedder(predictions.argmax(-1))
            embedded_output_2 = self.pos_encoder(embedded_output_2)
            tgt_mask_2 = self._generate_square_subsequent_mask(output_len).to(self.device)
            decoder_output_2 = self.transformer_decoder(tgt=embedded_output_2,
                                                    memory=src_output,
                                                    tgt_mask=tgt_mask_2)
            predictions_2 = self.fc_out(decoder_output_2)
            return F.log_softmax(predictions_2, dim=-1) 

        else:
            # predictions = torch.zeros(output_len-1, batch_size, self.vocab_size).to(self.device)
            output = torch.full((1, batch_size), 2, dtype=torch.long, device=self.device, requires_grad=False)
            # output =  torch.Variable(LongTensor([1, batch_size]), requires_grad=False).to(self.device)

            for i in range(output_len):
                embedded_output = self.tgt_embedder(output)
                embedded_output = self.pos_encoder(embedded_output)
                tgt_mask = self._generate_square_subsequent_mask(i+1).to(self.device)
                decoder_output = self.transformer_decoder(tgt=embedded_output,
                                                    memory=src_output,
                                                    tgt_mask=tgt_mask)
                prediction = self.fc_out(decoder_output[-1])
                prediction = F.log_softmax(prediction, dim=-1)
                decoder_outputs.append(prediction)
                # output[i+1] = prediction.topk(1)[1].long().view(-1, batch_size)
                output =  torch.cat((output, prediction.topk(1)[1].long().view(-1, batch_size)), dim=0)
        return decoder_outputs









